/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.alibaba.fastjson.JSONArray;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.emergency.domain.ContingencyPlan;
import com.koron.emergency.domain.ResponseLevel;
import com.koron.emergency.service.api.ContingencyPlanService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "contingencyPlan", description = "应急预案接口类")
@RestController
@RequestMapping("/contingencyPlan")
public class ContingencyPlanController {

    @Autowired
    private ContingencyPlanService contingencyPlanService;
    private final static Logger logger = LoggerFactory.getLogger(ContingencyPlanController.class);
    @Autowired
    private Util util;


    @ApiOperation("保存应急预案接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanName", value = "预案名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "version", value = "版本号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanCode", value = "应急预案编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanType", value = "预案类型", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "subordinateCompanyCode", value = "所属单位code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "subordinateCompanyName", value = "所属单位名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "publicationDate", value = "发布日期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "executionDate", value = "实施日期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "filingDate", value = "备案时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "applicableProvisions", value = "适用条款", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sortOrdinal", value = "排序序号，整数1-100,默认1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepFiles", value = "要保留的附件，多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepPDFFiles", value = "要保留的PDF附件，多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFiles", value = "要删除的附件，多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delPDFFiles", value = "要删除的PDF附件，多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态,提交传1.审核中,保存传2草稿", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "ResponseLevels", value = "响应等级信息(JSON格式字符串， [{'level':'响应等级，0-一级，1-二级，2-三级，3-四级','typeId':'类型id'," +
                    "'typeName':'类型名称','description':'响应等级描述', 'managerCode':'负责人code,可存在多个,存储格式为json','managerName':'责任人名称,可存在多个,存储格式为json'," +
                    "'senderCode':'通知人code,可存在多个,存储格式为json','senderName':'通知人名称,可存在多个,存储格式为json','organizationCode':'通知组织code,可存在多个,存储格式为json'," +
                    "'organizationName':'通知组织名称,可存在多个,存储格式为json','content':'通知内容'}])", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人code集合字符串", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "jobsTasksId", value = "工作任务id", paramType = "query", dataType = "String")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存应急预案", businessModule = "应急预案", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String usercode, @ApiIgnore ContingencyPlan bean,
                                     @ApiIgnore String ResponseLevels,
                                     @RequestParam(required = false) final String keepFiles,
                                     @RequestParam(required = false) final String keepPDFFiles,
                                     @RequestParam(required = false) final String delFiles,
                                     @RequestParam(required = false) final String delPDFFiles,
                                     @RequestParam(required = false) final MultipartFile[] files,
                                     @RequestParam(required = false) String jobsTasksId,
                                     String approverCodeListStr) {
        if (null == user) {
            //用于解决postman测试文件上传试的登陆问题
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(usercode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        //查看是否登陆
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        //判断响应等级字符串是否有数据
        if (StringUtils.isEmpty(ResponseLevels) || "[]".equals(ResponseLevels)) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("响应等级信息栏不能为空");
            return messageBean;
        }
        // 响应等级信息
        List<ResponseLevel> responseLevelList =JSONArray.parseArray(ResponseLevels, ResponseLevel.class);
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(new Date());
        return contingencyPlanService.save(bean, responseLevelList, keepFiles, keepPDFFiles, delFiles, delPDFFiles, files, user, approverCodeListStr, jobsTasksId);
    }

    @ApiOperation("删除应急预案接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急预案id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人code集合字符串，草稿不传，审核通过传", paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除应急预案",businessModule = "应急预案", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteContingencyPlan(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                      @RequestParam(required = false) String usercode,
                                                      @RequestParam final String id,
                                                      @RequestParam(required = false) String approverCodeListStr) {
        if (null == user)
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        return contingencyPlanService.delete(id, user, approverCodeListStr);
    }

    @ApiOperation("查询应急预案详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急预案id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<ContingencyPlan> details(@RequestParam final String id) {

        return contingencyPlanService.queryOne(id);
    }

    @ApiOperation("根据应急预案id查询响应等级详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急预案id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryResponseLevel.htm", method = RequestMethod.POST)
    public MessageBean<List<ResponseLevel>> queryResponseLevel(@RequestParam final String id) {
        return contingencyPlanService.queryByContingencyPlanId(id);
    }

    @ApiOperation("根据应急预案id获取应急预案下的响应等级信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应急预案id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/getResponseLevel.htm", method = RequestMethod.GET)
    public MessageBean<Map> getResponseLevel(@RequestParam final String id) {
        return contingencyPlanService.getResponseLevel(id);
    }

    @ApiOperation("应急预案列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanName", value = "应急预案名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanType", value = "应急预案类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<ContingencyPlan>> list(@RequestParam(required = false) final String corpCode,
                                                       @RequestParam(required = false) final String contingencyPlanName,
                                                       @RequestParam(required = false) final String contingencyPlanType,
                                                       @RequestParam Integer page,
                                                       @RequestParam Integer pageSize) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<ContingencyPlan>> msg = contingencyPlanService.list(corpCode, contingencyPlanName, contingencyPlanType, start, pageSize);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("演练计划、应急响应---下拉选择应急预案接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanName", value = "应急预案名称", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryAll.htm", method = RequestMethod.POST)
    public MessageBean<List<ContingencyPlan>> queryAll(@RequestParam(required = false) final String corpCode,
                                                       @RequestParam(required = false) final String contingencyPlanName) {
        return contingencyPlanService.queryAll(corpCode, contingencyPlanName);
    }


    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids) {
        return contingencyPlanService.getProcessData(ids);
    }



    @ApiOperation("应急预案列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanName", value = "应急预案名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanType", value = "应急预案类型", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode,
                                    @RequestParam(required = false) final String contingencyPlanName,
                                    @RequestParam(required = false) final String contingencyPlanType) {
        if (null == user) {
            return null;
        }
        List<ContingencyPlan> list = contingencyPlanService.exportList(user, corpCode, contingencyPlanName,contingencyPlanType);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/contingencyPlanList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/contingencyPlanList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("应急预案列表", targetFile, "contingencyPlanList.btl", map);
    }
}
